<?php
namespace app\admin\controller;

use app\common\model\AlipayOrders as Model;
use app\common\validate\AlipayOrders as Validate;
use bigDream\thinkJump\Jump;
use think\facade\Config;
use think\facade\Request;
use think\response\Json;
use think\response\View;
use Yansongda\Pay\Pay;

class Orders
{
    /**
     * 订单列表
     * @return View|Json
     */
    public function index(): View|Json
    {
        if (Request::isGet()) return view();

        $query = Model::autoSearch()
            ->order('create_time', 'desc')
            ->append(['status_text', 'refund_status_text']);

        $result = $query->paginate(Request::param('limit', 20));

        return json([
            'code'  => 0,
            'msg'   => '获取成功',
            'count' => $result->total(),
            'data'  => $result->items()
        ]);
    }

    public function refund()
    {
        $result = Model::where('id', Request::param('id'))->find();
        if (null === $result) Jump::error('内容不存在');

        if (!Request::isAjax()) {
            return view('', [
                'result' => $result,
            ]);
        }

        $validate = (new Validate())->scene('refund');
        $data = Request::only($validate->getSceneField());
        if (!$validate->check($data)) Jump::error($validate->getError());

        if ($data['refund_money'] > $result['money']) Jump::error('退款金额不能大于订单金额');

        Model::startTrans();
        try {
            $result->save(['refund_status' => 1]);

            app('Administrator')->log()->save([
                'type' => 'orders.refund',
                'info' => 'ID:' . $result['id'] . ',金额:' . $data['refund_money']
            ]);

            Pay::config(Config::get('pay'));
            $response = Pay::alipay()->refund([
                'trade_no' => $result['trade_no'],
                'refund_amount' => $data['refund_money'],
            ]);

            if (10000 != $response->code) {
                throw new \Exception('支付网关[' . $response->sub_code . ']:' . $response->sub_msg);
            }

            Model::commit();
        } catch (\Exception $e) {
            Model::rollback();

            Jump::error($e->getMessage());
        }

        Jump::success('退款成功');
    }
}